﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectProduct : CCSkinMain
    {
        private List<Product> productList = new List<Product>();
        public Product SelectedProduct { get; private set; }

        public SelectProduct()
        {
            InitializeComponent();
            InitializeForm();
            SetFormIcon();
        }

        private async void InitializeForm()
        {
            this.Text = "产品选择";
            this.Size = new Size(900, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 加载产品数据
            await LoadProductData();
        }
        /// <summary>
        /// 设置窗体图标
        /// </summary>
        private void SetFormIcon()
        {

            string[] possiblePaths = {
                    System.IO.Path.Combine(Application.StartupPath, "..", "..", "Images", "ss.ico")
                };

            string iconPath = possiblePaths.FirstOrDefault(System.IO.File.Exists);
            if (!string.IsNullOrEmpty(iconPath))
            {
                this.Icon = new System.Drawing.Icon(iconPath);
            }

        }
        /// <summary>
        /// 加载产品数据
        /// </summary>
        private async Task LoadProductData()
        {
            try
            {
                var response = await ApiRequestHelper.GetAsync<ApiResponse>("api/Plan/GetProduct");

                if (response.Success && response.Data?.code == 200 && response.Data.data != null)
                {
                    productList = response.Data.data.Select(p => new Product
                    {
                        ProductId = p.productId,
                        ProductCode = p.productCode,
                        ProductName = p.productName,
                        Specification = p.specification,
                        UnitName = p.unitName
                    }).ToList();
                    LoadProductDataToGrid();
                }
                else
                {
                    var errorMsg = response.Data?.msg ?? response.Message;
                    ApiRequestHelper.ShowError($"加载产品数据失败: {errorMsg}");
                }
            }
            catch (Exception ex)
            {
                ApiRequestHelper.ShowError($"加载产品数据异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 将产品数据加载到DataGridView
        /// </summary>
        private void LoadProductDataToGrid()
        {
            try
            {
                if (productList == null || productList.Count == 0)
                {
                    ShowAlert("暂无产品数据", "提示");
                    return;
                }

                // 绑定数据到DataGridView
                dgvProducts.AutoGenerateColumns = false;
                dgvProducts.DataSource = productList;

                // 默认选中第一行
                if (dgvProducts.Rows.Count > 0)
                {
                    dgvProducts.Rows[0].Selected = true;
                    dgvProducts.CurrentCell = dgvProducts.Rows[0].Cells[0];
                }

            }
            catch (Exception ex)
            {
                ShowAlert(string.Format("加载产品数据到表格失败: {0}", ex.Message), "错误");
            }
        }



        /// <summary>
        /// 确认选择按钮
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvProducts.SelectedRows.Count > 0)
                {
                    var selectedRow = dgvProducts.CurrentRow.Index;

                    if (selectedRow >= 0 && selectedRow < productList.Count)
                    {
                        SelectedProduct = productList[selectedRow];
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        ShowAlert("请选择有效的产品", "提示");
                    }
                }
                else
                {
                    ShowAlert("请先选择一个产品", "提示");
                }
            }
            catch (Exception ex)
            {
                ShowAlert(string.Format("选择产品失败: {0}", ex.Message), "错误");
            }
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        private void ShowAlert(string message, string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK,
                caption == "成功" ? MessageBoxIcon.Information
                : caption == "提示" ? MessageBoxIcon.Information
                : MessageBoxIcon.Error);
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void dgvProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }

}

